//
//  OnlinePkVC.swift
//  MM2
//
//  Created by 李成明 on 2022/1/13.
//

import UIKit
import CLImagePickerTool

private class InputNumItem: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        isUserInteractionEnabled = false
        layer.masksToBounds = true
        layer.borderColor = UIColor.black.cgColor
        layer.borderWidth = 0.5
        
        addSubview(numLabel)
        numLabel.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var numLabel: UILabel = {
        let view = UILabel()
        view.font = .systemFont(ofSize: 25)
        view.textAlignment = .center
        return view
    }()
    
    var value: Character? {
        didSet {
            numLabel.text = (value == nil) ? "" : "\(value!)"
        }
    }
}

private class HouseNumInputView: UIView, UITextFieldDelegate {
    override init(frame: CGRect) {
        self.viewHeight = frame.size.height
        self.viewWidth = frame.size.width
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var houseNumEn: Bool =  false
    var houseNumValue: Int? {
        return Int(textView.text ?? "")
    }
    private let viewHeight: CGFloat
    private let viewWidth: CGFloat
    private var itemArry: [InputNumItem] = []
    private lazy var textView: UITextField = {
        let view = UITextField()
        view.font = textFont
        view.delegate = self
        view.tintColor = .white
        view.textColor = .white
        view.keyboardType = .numberPad
        return view
    }()
    
    private func setupUI() {
        addsubViews([textView])
        textView.frame = bounds
        
        var x: CGFloat = 0
        let space: CGFloat = 8
        let itemW: CGFloat = (viewWidth - space*3)/4
        for _ in 1...4 {
            let item = InputNumItem(frame: CGRect(x: x, y: 0, width: itemW, height: viewHeight))
            itemArry.append(item)
            x += (itemW + space)
        }
        self.addsubViews(itemArry)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string.count == 0 { return true }
        if (textField.text?.count ?? 0) + string.count > 4 || !Util.isLetterWithDigital(string) { return false }
        return true
    }
    
    func textFieldDidChangeSelection(_ textField: UITextField) {
        guard let str = textField.text else { return }
        itemArry.forEach { $0.value = nil }
        var numArr: [Character] = []
        str.forEach{ numArr.append($0) }
        updateValue(numArr)
        houseNumEn = (numArr.count >= 4)
    }
    
    private func updateValue(_ arr: [Character], index: Int = 0) {
        if !arr.isEmpty {
            let item = arr.first!
            itemArry[index].value = item
            
            var tempArr = arr
            tempArr.removeFirst()
            
            updateValue(tempArr, index: (index + 1))
        }
    }
}

class OnlinePkVC: MViewController {

    deinit {
        timer?.invalidate()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    private var imgEn = false
    private var isRequestingResult = false
    private var timer: Timer?
    private var isUploaded = false {
        didSet {
            beginBtn.isUserInteractionEnabled = false
            beginBtn.setTitleColor(mainColor, for: .normal)
            beginBtn.layer.borderColor = UIColor.initWithRGB(215, 100, 72).cgColor
        }
    }
    
    private lazy var navBar: MNavBar = {
        let view = MNavBar(frame: CGRect(x: 0, y: kStateBarHeight, width: kScreenWidth, height: kNaviBarHeight))
        view.back { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }.title = "实时PK"
        return view
    }()
    
    private lazy var numInputView: HouseNumInputView = {
        let viewWidth: CGFloat = 150
        let view = HouseNumInputView(frame: CGRect(x: kScreenWidth/2 - viewWidth/2, y: kStateAndNavH + 150, width: viewWidth, height: 40))
        return view
    }()
    
    private lazy var titleLabel: UILabel = {
        let view = UILabel()
        view.text = "输入房间号"
        view.font = .systemFont(ofSize: 16)
        view.textAlignment = .center
        return view
    }()
    
    private lazy var addPhotoImg: UIImageView = {
        let img = UIImageView(image: UIImage(named: "rank_add_photo_img"))
        img.frame = CGRect(x: kScreenWidth - 200, y: 50, width: 150, height: 150)
        img.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(addPhotoAction))
        img.addGestureRecognizer(tap)
        img.layer.masksToBounds = true
        img.layer.cornerRadius = 10
        img.contentMode = .scaleAspectFit
        return img
    }()
    
    private lazy var beginBtn: UIButton = {
        let view = UIButton()
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 8
        view.layer.borderWidth = 1
        view.layer.borderColor = UIColor.initWithRGB(215, 100, 72).cgColor
        view.titleLabel?.font = .systemFont(ofSize: 20)
        view.setTitleColor(.initWithRGB(215, 100, 72), for: .normal)
        view.setTitle("开始PK", for: .normal)
        view.addTarget(self, action: #selector(beginBtnClick), for: .touchUpInside)
        return view
    }()
}

extension OnlinePkVC {
    private func setupUI() {
        view.addsubViews([navBar, titleLabel, numInputView, addPhotoImg, beginBtn])
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(numInputView).offset(-40)
            make.centerX.equalTo(numInputView)
        }
        
        addPhotoImg.snp.makeConstraints { make in
            make.top.equalTo(numInputView.snp.bottom).offset(30)
            make.centerX.equalTo(numInputView)
            make.size.equalTo(CGSize(width: 180, height: 180))
        }
        
        beginBtn.snp.makeConstraints { make in
            make.top.equalTo(addPhotoImg.snp.bottom).offset(20)
            make.centerX.equalTo(addPhotoImg)
            make.size.equalTo(CGSize(width: 100, height: 40))
        }
    }
    
    @objc private func addPhotoAction() {
        let imgTool = CLImagePickerTool()
        imgTool.singleImageChooseType = .singlePicture
        imgTool.cl_setupImagePickerWith(MaxImagesCount: 1, superVC: self) { asset, image in
            CLImagePickerTool.convertAssetArrToOriginImage(assetArr: asset, scale: 1) { img, _ in
                self.addPhotoImg.image = img
                self.imgEn = true
            } failedClouse: {
                self.view.showToast(text: "既然看到了这个，那应该是出bug了")
            }
        }
    }
    
    @objc private func beginBtnClick() {
        if numInputView.houseNumEn && imgEn {
            view.showToast(text: "正在为寻找房间")
            FaceManager.share.faceDetect(image: addPhotoImg.image!) { num in
                if num > 1 {
                    self.view.showToast(text: "检测出多张图片，将为你分析第一章")
                }
            } complete: { model in
                guard let model = model, let image = self.addPhotoImg.image, let imageData = Util.compressImageData(img: image) else { return }
                let path = "image/\(User.share.userId)/\(Util.randomString())"
                OSSManager.share.uploadSingleImg(data: imageData, path: path) { imgUrl in
                    self.uploadFaceResult(model: model, imgUrl: imgUrl)
                }
            }
        }
    }
    
    private func uploadFaceResult(model: FaceUseResultModel, imgUrl: String) {
        if isUploaded { return }
        isUploaded = true
        
        guard let houseNum = numInputView.houseNumValue else { return }
        MoyaNetwork.request(target: BaseApi.uploadOnlinPk(housenum: houseNum, model: model, imgUrl: imgUrl)) { _, _ in
            self.beginResultRequest()
        }
    }
    
    private func beginResultRequest() {
        timer = Timer.scheduledTimer(timeInterval: 0.25, target: self, selector: #selector(requestOnlinePkResult), userInfo: nil, repeats: true)
    }
    
    @objc private func requestOnlinePkResult() {
        if isRequestingResult { return }
        isRequestingResult = true
        
        guard let houseNum = numInputView.houseNumValue else { return }
        MoyaNetwork.request(target: BaseApi.onlinePkResult(hoursenum: houseNum)) { [weak self] json, Json in
            guard let self = self else { return }
            self.isRequestingResult = false
            
            let result = json["result"].boolValue
            if result {
                self.timer?.invalidate()
                let model = OnlinePkModel.deserialize(from: json["data"].dictionaryObject)
                guard let model1 = model?.user1, let model2 = model?.user2 else { return }
                let selfmodel = (model1.userId == User.share.userId) ? model1 : model2
                let pkUserModel = model1 === selfmodel ? model2 : model1
                let vc = OnliePkResultVC(selfModel: selfmodel, pkUserModel: pkUserModel)
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
}
